package de.gwtprime.server.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import de.gwtprime.server.sql.helper.HibernateHelper;
import de.gwtprime.shared.util.AppUtilsShared;

public class MailSender {

	
	private static Logger logger = Logger.getLogger(MailSender.class.getName());
	
	public static void sendMailToAdmin(String subject, String text){
		sendMail("janpumpe@googlemail.com", subject, text);
		 
			
	}
	
	public static void sendMail(String recipient, String subject, String text){
		
		// Don't send mails during unit test
		if(HibernateHelper.test){
			return;
		}
		
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = text;

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(AppUtilsShared.mailSenderAdress, AppUtilsShared.websiteTitle));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(recipient, recipient));
            msg.setSubject(subject);
            msg.setText(msgBody);
            Transport.send(msg);

        } catch (AddressException e) {
            logger.warning(e.toString());
        } catch (MessagingException e) {
        	logger.warning(e.toString());
        } catch (UnsupportedEncodingException e) {
        	logger.warning(e.toString());
		}
	}
}
